using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CoreCalc.SheetDefinedFunctions;

namespace CoreCalc.GUI
{
  public partial class AddSDF : Form
  {
    private Workbook wb;

    public AddSDF(Workbook wb)
    {
      this.wb = wb;
      InitializeComponent();
      PopulateSheetList();
    }

    private void PopulateSheetList()
    {
      if (wb != null)
        foreach (Sheet sheet in wb)
          if (sheet.IsFunctionSheet)
            sheetsComboBox.Items.Add(sheet);
    }

    private void addCellButton_Click(object sender, EventArgs e)
    {
      if (addTextBox.Text != string.Empty)
      {
        inputCellsListBox.Items.Add(addTextBox.Text);
        addTextBox.Text = string.Empty;
      }
    }

    private void okButton_Click(object sender, EventArgs e)
    {
      if (sheetsComboBox.SelectedItem != null
          && outputTextBox.Text != string.Empty
          && inputCellsListBox.Items.Count != 0 &&
          nameTextBox.Text != string.Empty)
        CreateMethod();
      else
        StandardErrorBox();
    }

    private void CreateMethod()
    {
      Sheet sheet = (Sheet)sheetsComboBox.SelectedItem;
      List<FullCellAddr> inputCells = new List<FullCellAddr>();
      foreach (string s in inputCellsListBox.Items)
        inputCells.Add(new FullCellAddr(s, sheet));
      FullCellAddr outputCell = new FullCellAddr(outputTextBox.Text, sheet);
      string methodName = nameTextBox.Text;
      if (!SdfManager.CreateFunction(methodName, outputCell, inputCells))
        MessageBox.Show("Method name already exists", "Duplicate Method");
    }

    private void StandardErrorBox()
    {
      MessageBox.Show("Some parameters where wrong or empty", "Information is missing or contains error");
    }

    private void sheetsComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
  }
}